﻿#include "ChaosLogManager.hpp"
#include "ChaosLogFile.hpp"
#include "ChaosLogConsole.hpp"

#include <sstream>

namespace Chaos
{
	ChsLogManager::ChsLogManager()
	{
		AddLogger(CONSOLELOGGER,new ChsLogConsole());
		AddLogger(LOGFILELOGGER,new ChsLogFile(_T("log.txt")));
		AddLogger(ERRORFILELOGGER,new ChsLogFile(_T("error.txt")));
		LOGMSG("Log Manager online.");
	}

	ChsLogManager::~ChsLogManager()
	{
		LOGMSG("Log Manager offline.");
		RemoveLoggerAll();
	}
	void	ChsLogManager::AddLogger(const std::wstring& name,ChsLog* pLogger)
	{
		m_loggers.insert(make_pair(name,pLogger));
	}
	
	void ChsLogManager::RemoveLogger(const std::wstring& name)
	{
		ChsLoggerList::iterator iter;
		if( ( iter = m_loggers.find(name) ) != m_loggers.end() )
		{
			delete iter->second;
			m_loggers.erase(iter);
		}
	}
	
	void ChsLogManager::RemoveLoggerAll()
	{
		for(ChsLoggerList::iterator iter = m_loggers.begin();iter!=m_loggers.end();iter++)
		{
			delete iter->second;
		}
		m_loggers.erase(m_loggers.begin(),m_loggers.end());
	}


	#include <strsafe.h>

	void ChsLogManager::DoLog(const std::wstring & name,const LPCTSTR msgText,...)
	{

		va_list args;
		va_start(args, msgText);
		StringCchVPrintf( m_chBuffer, 512, msgText, args );
		m_chBuffer[511] = _T('\0');
		va_end(args);

		std::wostringstream logMsg;

		//得到当前本地的系统时间
		GetLocalTime(&m_systemTime);

		//添加时间，格式化信息
		logMsg << _T("[") <<	
			m_systemTime.wYear << _T("-") <<
			m_systemTime.wMonth << _T("-") <<
			m_systemTime.wDay << _T(" ") <<
			m_systemTime.wHour << _T(":") <<
			m_systemTime.wMinute << _T(":") << 
			m_systemTime.wSecond <<
			_T("]") << m_chBuffer << endl;

		

		ChsLoggerList::const_iterator iter;
		if( (iter = m_loggers.find(name)) != m_loggers.end())
		{
			ChsLog* pLogger = iter->second;
			pLogger->m_strLogCache+=logMsg.str();
			pLogger->Update();
		}

		if( (iter = m_loggers.find(CONSOLELOGGER)) != m_loggers.end())
		{
			ChsLog* pLogger = iter->second;
			pLogger->m_strLogCache+=logMsg.str();
			pLogger->Update();
		}
	}

}//namespace Chaos

